﻿#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    table=TD_UNIT;
    initialize();
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::initialize()
{
    QSqlQuery query;
    query.exec(QString("select category from %1 GROUP BY category").arg(table));
    while (query.next()) {
        categories.append(query.value("category").toString());
    }
    if(!categories.isEmpty())
    {
        ui->category->addItems(categories);
        ui->category->setCurrentIndex(-1);

        loadItems();
    }
    else
        QMessageBox::warning(this,QStringLiteral("类别为空"),QStringLiteral("没有有效类别！"));
}

void Dialog::loadItems()
{
    QSqlQuery query;
    query.exec(QString("select label,offset from %1").arg(table));
    while (query.next()) {
        QString label=query.value("label").toString();
        bool ok;
        double offset=query.value("offset").toDouble(&ok);
        if(!ok)
            offset=1;
        items.insert(label,offset);
    }
}

void Dialog::on_btn_convert_clicked()
{
    if(ui->source->currentIndex() == -1 || ui->destination->currentIndex() == -1)
        return;

    if(categories.isEmpty() || items.isEmpty())
        return;


    bool ok;
    double input=ui->input->text().toDouble(&ok);
    if(!ok)
        input=1;

    QString source=ui->source->currentText();
    QString destination=ui->destination->currentText();

    double xValue=items.value(source);
    double yValue=items.value(destination);
    double zValue=xValue / yValue * input;
    ui->output->setText(QString::number(zValue));
}

void Dialog::on_category_currentTextChanged(const QString &arg1)
{
    ui->source->clear();
    ui->destination->clear();

    QSqlQuery query;
    query.exec(QString("select label from %1 where category='%2'")
               .arg(table)
               .arg(arg1));
    while (query.next()) {
        ui->source->addItem(query.value("label").toString());
        ui->destination->addItem(query.value("label").toString());
    }
    ui->source->setCurrentIndex(-1);
    ui->destination->setCurrentIndex(-1);
}

void Dialog::on_btn_exchange_clicked()
{
    if(ui->source->currentIndex() == -1 || ui->destination->currentIndex() == -1)
        return;

    if(categories.isEmpty() || items.isEmpty())
        return;

    QString source=ui->source->currentText();
    QString destination=ui->destination->currentText();
    ui->source->setCurrentText(destination);
    ui->destination->setCurrentText(source);
}
